<template>
  <el-card style="height: 100%;">
    <div>
      <!--      <span>Using slots</span>-->
      <el-input
        style="width: 240px"
        placeholder="角色名称"
        v-model="searchList.name"
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <!--      <span>Using slots</span>-->
      <el-input
        style="width: 240px"
        placeholder="角色权限字符串"
        v-model="searchList.code"
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <!--      <span>Using slots</span>-->
      <el-button type="primary" :icon="Search" round @click="GetRoleInfo">搜索</el-button>
      <el-button v-if="PERMISSION_BUTTON.CREATE" type="success" plain round @click="showData($event, false, false)">
        新增角色
      </el-button>
      <el-button v-if="PERMISSION_BUTTON.DELETE_LIST" @click="handleDelete(SelectionUserInfo)" type="danger" plain
                 round>批量删除
      </el-button>
    </div>
    <el-table :data="RoleInfoList" stripe style="font-size:15px" @row-dblclick="showData($event, true, false)"
              @selection-change="SelectionUserInfo = $event.map((item) => item.ID)">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="编号" width="100" type="index" align="center"/>
      <el-table-column prop="NAME" label="角色名称"/>
      <el-table-column prop="CODE" label="角色权限字符串"/>
      <el-table-column prop="REMARK" label="备注"/>
      <el-table-column align="center" label="操作" min-width="150">
        <template #default="scope">
          <el-button v-if="PERMISSION_BUTTON.UPDATE" size="small" type="primary"
                     @click.stop="showData(scope.row, false, true)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click.stop="handleDelete(scope.row)"
            v-if="PERMISSION_BUTTON.DELETE"
          >
            删除
          </el-button>
          <el-button v-if="PERMISSION_BUTTON.ASSIGN" size="small" type="success"
                     @click.stop="beforeHandleAssign(scope.row)">
            分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogFormVisible" width="500">
      <el-form :model="form">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="角色权限字符串" :label-width="formLabelWidth">
          <el-input v-model="form.code" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogFormTreeVisible">
      <el-tree
        ref="treeRef"
        :props="props"
        :data="MenuInfoList"
        show-checkbox
        default-expand-all
        node-key="ID"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormTreeVisible = false">取消</el-button>
          <el-button type="primary" @click.stop="handleAssign">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>

import { useStore } from 'vuex';
import { onBeforeMount, reactive, ref, toRefs } from 'vue';
import { get, post } from '../../api/https';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { flatten, hasPermission } from '@/utils';
import { ROLE } from '@/utils/permission';

export default {
  name: 'RoleView',
  setup() {
    const store = useStore();
    const data = reactive({
      RoleInfoList: [],
      MenuInfoList: [],
      SelectionUserInfo: [],
      SelectionMenuInfo: [],
      props: {
        label: 'NAME',
        children: 'children'
      },
      form: {
        id: '',
        name: '',
        code: '',
        remark: '',
      },
      formLabelWidth: 80,
      searchList: {
        name: '',
        code: '',
      },
      PERMISSION_BUTTON: {
        CREATE: false,
        UPDATE: false,
        DELETE: false,
        DELETE_LIST: false,
        ASSIGN: false
      }
    });

    let dialogFormVisible = ref(false);
    let dialogFormTreeVisible = ref(false);
    let dialogDisabled = ref(false);
    let isEdit = ref(false);
    const treeRef = ref(null);
    let roleId = ref('');

    async function defaultCheckList(role_id) {
      roleId.value = role_id;
      const response = await get('/menu/get-menu-list-by-role-id/', {
        id: role_id
      });
      if (response.code == 200) {
        treeRef.value.setCheckedKeys(response.data);
      } else {
        ElMessage({
          // message: '获取当前用户权限信息失败',
          message: response.data.message,
          type: 'warning'
        });
        dialogFormTreeVisible.value = false;
      }
    }

    //获取权限信息
    async function GetTreeList() {
      const response = await get('/menu/get-tree-list/');
      if (response.code == 200) {
        data.MenuInfoList = response.data;
      } else {
        ElMessage({
          message: '获取权限信息失败',
          type: 'warning'
        });
      }
    }

    async function GetRoleInfo() {
      let response = await get('/role/get-list/', data.searchList);
      if (response.code == 200) {
        data.RoleInfoList = response.data;
      } else {
        ElMessage({
          message: '获取角色信息失败',
          type: 'warning'
        });
      }
    }

    onBeforeMount(async () => {
      await GetRoleInfo();
      await GetTreeList();
      data.PERMISSION_BUTTON.CREATE = await hasPermission(ROLE.SYSTEM_ROLE_CREATE);
      data.PERMISSION_BUTTON.UPDATE = await hasPermission(ROLE.SYSTEM_ROLE_UPDATE);
      data.PERMISSION_BUTTON.DELETE = await hasPermission(ROLE.SYSTEM_ROLE_DELETE);
      data.PERMISSION_BUTTON.DELETE_LIST = await hasPermission(ROLE.SYSTEM_ROLE_DELETE_LIST);
      data.PERMISSION_BUTTON.ASSIGN = await hasPermission(ROLE.SYSTEM_ROLE_ASSIGN);
    });

    function handleEdit() {
      if (dialogDisabled.value) {
        return;
      }
      ElMessageBox.confirm(`是否确认${isEdit.value ? '修改' : '添加'}当前角色信息`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
        // center: true,
        // roundButton: true,
      })
        .then(async () => {
          const response = await post(`${isEdit.value ? '/role/update/' : '/role/create/'}`, data.form);
          if (response.code == 200) {
            dialogFormVisible.value = false;
            await GetRoleInfo();
            ElMessage({
              message: `${isEdit.value ? '修改' : '添加'}角色信息成功`,
              type: 'success',
            });
          } else {
            dialogFormVisible.value = false;
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
        });
    }

    function handleDelete(row) {
      ElMessageBox.confirm('确定删除当前记录？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
      })
        .then(async () => {
          let deleteIdList = [];
          if (row instanceof Array) {
            deleteIdList.push(...row);
          } else if (row instanceof Object) {
            deleteIdList.push(row.ID);
          }
          if (deleteIdList.length == 0) {
            ElMessage({
              message: '请选择需要删除的信息',
              type: 'warning',
            });
            return;
          }
          const response = await post('/role/delete-list/', deleteIdList);
          if (response.code == 200) {
            await GetRoleInfo();
            ElMessage({
              message: `成功删除 ${response.data.count} 条记录`,
              type: 'success',
            });
          } else {
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
        });
    }

    async function beforeHandleAssign(row) {
      dialogFormTreeVisible.value = true;
      await defaultCheckList(row.ID);
    }

    function handleAssign() {
      let keys = treeRef.value.getCheckedKeys();
      keys.push(...treeRef.value.getHalfCheckedKeys());
      ElMessageBox.confirm('确认为当前角色分配权限', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
      })
        .then(async () => {
          const response = await post('/role/assigning-permissions/', {
            'roleId': roleId.value,
            'menuIdList': keys
          });
          if (response.code == 200) {
            dialogFormTreeVisible.value = false;
            ElMessage({
              message: `角色分配权限成功`,
              type: 'success',
            });
            //分配权限成功后，获取当前用户最新权限
            const {
              code,
              data
            } = await get('/user/get-menu-by-username/', {
              username: localStorage.getItem('user'),
              isGetRole: false
            });
            if (code == 200) {
              store.state.Permissions = flatten(data)
                .filter((item) => item.MENU_TYPE == 3)
                .map(item => item.PERMS);
            } else {
              ElMessage({
                type: 'error',
                message: response.data.message
              });
            }
          } else {
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
        });
    }

    function showData(row, disabled, edit) {
      dialogFormVisible.value = true;
      dialogDisabled.value = disabled;
      isEdit.value = edit;
      if (!isEdit.value && !dialogDisabled.value) {
        data.form.id = '';
        data.form.name = '';
        data.form.code = '';
        data.form.remark = '';
      } else {
        data.form.id = row.ID;
        data.form.name = row.NAME;
        data.form.code = row.CODE;
        data.form.remark = row.REMARK;
      }
    }

    return {
      ...toRefs(data),
      dialogFormVisible,
      dialogFormTreeVisible,
      dialogDisabled,
      isEdit,
      treeRef,
      handleEdit,
      handleDelete,
      beforeHandleAssign,
      handleAssign,
      showData,
      dayjs,
      defaultCheckList,
      GetRoleInfo,
      Search,
    };
  },
};
</script>

<style scoped>
.el-input {
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 5px;
  margin-bottom: 10px;
}
</style>
